package cn.tedu.micro.demo.emqx.mqtt;

import cn.tedu.micro.demo.emqx.serializer.MessageSerializer;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MqttProducer<T> {
    @Autowired
    private MqttClient mqttClient;
    @Autowired
    private MessageSerializer messageSerializer;
    public void send(String topic,T msg,int qos,boolean retained){
        byte[] payload = messageSerializer.serialize(msg);
        try{
            mqttClient.publish(topic,payload,qos,retained);
        }catch(Exception e){
            log.error("发送消息失败",e);
        }
    }
    public void send(String topic,T msg) {
        this.send(topic, msg, 1, true);
    }
}
